import SparkMd5 from 'spark-md5'
import axios from 'axios';

/**
 * 将文件分片的方法
 * @param file:文件
 */
const CHUNK_SIZE=1024*1024*5;
export const createFileChunks=(file:File)=>{
    const chunkList=[]
    const chunkCount=Math.ceil(file.size/CHUNK_SIZE)
    for(let i=0;i<chunkCount;i++){
        chunkList.push(file.slice(i*CHUNK_SIZE,(i+1)*CHUNK_SIZE))
    }
    return chunkList
}

export const calcFileHash=(file:Blob)=>{
    return new Promise((resolve)=>{
        const spark=new SparkMd5.ArrayBuffer()
        const fileReader=new FileReader()
        fileReader.readAsArrayBuffer(file)
        fileReader.onload=(e:any)=>{
            spark.append(e.target.result)
            resolve(spark.end())

        }   
    })
}
/**
 * 计算一个chunks切片数组的的hash值
 * @param chunks 
 */
export const calcChunksHash=(chunks:Array<Blob>)=>{
    return new Promise((resolve)=>{
        const spark=new SparkMd5.ArrayBuffer()
        const fileReader=new FileReader()
        const targets:Array<Blob>=[]
        chunks.forEach((chunk:Blob,index:number)=>{
            if(index===0||index===chunks.length-1){
                targets.push(chunk)
            }else{
                targets.push(chunk.slice(2,4))
                targets.push(chunk.slice(CHUNK_SIZE/2,CHUNK_SIZE/2+2))
                targets.push(chunk.slice(CHUNK_SIZE-3,CHUNK_SIZE-1))
            }
        })        

        fileReader.readAsArrayBuffer(new Blob(targets))
        fileReader.onload=(e:any)=>{
            spark.append(e.target.result)
            resolve(spark.end())

        }   

    })
}
/**
 * 分片上传
 * @param chunks 
 */
export const uploadChunks=(chunks:Array<Blob>,hash:unknown,suffix:string)=>{
    // 定义count变量，用来成功上传了多少个切片
    let count=0;
    //遍历所有的chunks
    chunks.forEach((chunk:Blob,index:number)=>{
        const formData=new FormData()
        formData.append('chunk',chunk)
        formData.append('chunkName',`${hash}-${index}`)
        axios({
            method:'POST',
            url:'http://localhost:3000/upload/upload_chunk',
            data:formData,
            headers:{
                'Content-Type':'multipart/form-data'
            }
        }).then(res=>{
           if(res.status===200){
             count++
           }
           if(count===chunks.length){
             axios({
                url:'http://localhost:3000/upload/upload_merge',
                params:{
                    hash,
                    suffix
                }
             }).then(res=>{
                
             })
           }
           
            
        })
    })   
}